<template>
  <div class="operationButton h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeData" ref="systemtree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleClick"
          ></el-tree>
        </el-col>
        <el-col :span="4" class="right-tree">
          <el-tree :data="menuData" ref="menutree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="menuHandleClick"
          ></el-tree>
        </el-col>
        <el-col :span="16"  class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button type="primary" v-if="btnRight.btnOperationButtonRefresh">刷新</el-button>
            <el-button type="primary" v-if="btnRight.btnOperationButtonAdd" @click="add()">添加</el-button>
            <el-button type="primary" v-if="btnRight.btnOperationButtonEdit" @click="modify()">修改</el-button>
            <el-button type="danger"  v-if="btnRight.btnOperationButtonDelete" @click="remove()">删除</el-button>
          </el-row>
          <el-table
            ref="btnTable"
            :data="tableData" :header-cell-style="{background:'rgb(222,225,230)',color:'#606266'}"
            row-key="id"
            border
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @row-click="handleRowClick"
            @select="select" @select-all="selectAll"
            style="width: 100%;height: calc(100% - 80px);overflow-y: scroll">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              property="buttonName"
              label="按钮名称"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="buttonDescribe"
              label="用途说明"
              align = 'center'>
            </el-table-column>
            <el-table-column
              property="disableState"
              label="状态"
              align = 'center'
              width="120">
              <template slot-scope="{row,$index}">
                <span v-if="row.disableState==0">有效可用</span>
                <span v-else-if="row.disableState==1">无效禁用</span>
              </template>
            </el-table-column>
            <el-table-column
              property="sort"
              align = 'center'
              label="顺序"
              width="120">
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px">
          </div>
        </el-col>
    </div>
    <el-dialog title="按钮信息维护" :visible.sync="dialogVisible" width="700px" v-dialogDrag   border >
      <el-form :model="saveData" :rules="rules" class="saveform" ref="btndialog" :inline="true" label-width="120px" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="业务系统:">
            <el-input v-model="saveData.businessSystemName" style="width:515px;" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="菜单模块:">
            <el-input v-model="saveData.businessSystemMenu" style="width:515px;" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="按钮名称:" prop="buttonName">
            <el-input v-model="saveData.buttonName" maxlength="50" style="width:515px;"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5" class="saveform" >
          <el-form-item label="用途说明:" prop="buttonDescribe">
            <el-input type="textarea"  style="width:515px;" v-model="saveData.buttonDescribe"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:" prop="disableState">
            <el-select v-model="saveData.disableState" style="width:515px;" placeholder="请选择" >
              <el-option
                v-for="item in disableState"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="排序:">
            <el-input  onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null" v-model="saveData.sort"  style="width:515px;" maxlength="11" ></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5" class="saveform" >
          <el-form-item label="备注:" >
            <el-input type="textarea"  style="width:515px;" v-model="saveData.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" v-if="btnRight.btnOperationButtonSave" @click="Save()" :disabled="saveFlag">保存</el-button>
        <el-button v-if="btnRight.btnOperationButtonCancel" @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import * as API from '@/api/stystemManagement'
  import {treeTransformate} from "../../utils/treeTransformate";

  export default {
    name: "operationButton",
    data(){
      return {
        rules: {
          buttonName: [{required: true, message: '请输入菜单按钮', trigger: 'blur'}],
          buttonDescribe: [{required: true, message: '请输入按钮描述', trigger: 'blur'}],
          disableState: [{required: true, message: '请选择禁用状态', trigger: 'blur'}],

        },
        treeData: [{
          id: 0,
          label: '殡葬业务平台',
          children: []
        }],
        menuData: [{
          id: 0,
          label: '菜单模块',
          children: []
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tableData: [],
        currentRow: null,
        tableSelection:[],
        saveFlag:false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        dialogVisible:false,//维护对话框
        disableState:[
          {label:"有效可用",value:0},{label:"无效禁用",value:1},
        ],
        saveData:{       //保存基本信息
          "id": 0,
          "businessSystemName":"",   //界面显示用不传后台
          "businessSystemMenu":"",   //界面显示用不传后台
          "businessSystemMenuId": 0,
          "buttonName": "string",
          "buttonDescribe": "string",
          "disableState": 0,
          "remark": "string",
          "sort": 0,
          "version": 0
        },btnRight: {
          btnOperationButtonAdd: true, //添加
          btnOperationButtonEdit: true,//修改
          btnOperationButtonDelete: true,//删除
          btnOperationButtonSave: true,//保存
          btnOperationButtonCancel: true,//取消
          btnOperationButtonRefresh: true,//刷新
        }
      }
    },
    mounted(){
      this.loadBusinessSystemListData()
      //载入按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //系统tree单选
      handleClick(data,checked, node){
        if(checked && data.label!="业务模块"){
          this.$refs.systemtree.setCheckedNodes([data]);
          // this.saveData.businessSystemName = data.label
          this.loadSystemMenuListWithBusinessSystemIdData(data.id)
        }
      },

      //菜单tree单选
      menuHandleClick(data,checked, node){
        if(checked && data.label!="菜单模块"){
          this.$refs.menutree.setCheckedNodes([data]);
          // this.saveData.businessSystemMenu = data.label
          // this.saveData.businessSystemMenuId = data.id
          this.loadButtonListWithMenuIdData(data.id)
        }
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.tableSelection.length>0){
          this.$refs.btnTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.btnTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.btnTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },
      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },

      //table中类型添加
      add(){
        let data = this.$refs.menutree.getCheckedNodes()
        //添加子系统的主菜单按钮
        if (data.length == 0){
          this.$message("未选中系统菜单")
          return
        }
        else{
          this.saveData ={
            "id": "",
            // "businessSystemMenuId": "",
            "buttonName": "",
            "buttonDescribe": "",
            "disableState": "",
            "remark": "",
            "sort": "",
            "version": ""
          }
          /*设置系统名称*/
          let system = this.$refs.systemtree.getCheckedNodes();
          this.saveData.businessSystemName = system[0].label
          /*设置菜单名称*/
          this.saveData.businessSystemMenu = data[0].label
          this.saveData.businessSystemMenuId = data[0].id
          this.dialogVisible = true
        }
      },
      modify(){
        let data = this.$refs.btnTable.selection
        if (data && data.length){
          this.loadButtonWithIdData(data[0].id).then( res => {
            if (res) {
              this.saveData = res
              /*设置系统名称*/
              let system = this.$refs.systemtree.getCheckedNodes();
              this.saveData.businessSystemName = system[0].label

              let menuData = this.$refs.menutree.getCheckedNodes()
              /*设置菜单名称*/
              this.saveData.businessSystemMenu = menuData[0].label

              this.dialogVisible = true
            } else {
              this.$message("数据加载失败")
            }
          })
        } else{
          this.$message("请选择菜单")
        }
      },
      //table中服务物品类型删除
      remove(){
        let data = this.$refs.btnTable.selection
        if (data.length==0) {
          this.$message("未选中按钮")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData=[]
          data.forEach(item=>{
            postData.push({
              "id": item.id,
              "version": item.version
            })
          })
          API['deleteButtonWithId'](postData).then(response=>{
            const { message }=response;
            this.$message(message)
            this.tableSelection = []
            let data = this.$refs.menutree.getCheckedNodes()
            this.loadButtonListWithMenuIdData(data[0].id)
          }).catch(error => {
            this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //加载系统列表
      loadBusinessSystemListData(){
        API['loadBusinessSystemList']().then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          if (data && data.length) {
            data.forEach(item=>{
              item.label = item.systemName
              this.treeData[0].children.push(item)
            })
          }
        }).catch(error => {
          this.$message(error)
        })
      },
      //根据业务系统id，加载系统下所有菜单列表
      loadSystemMenuListWithBusinessSystemIdData(code){
        let postData={
          "businessSystemId": code
        }
        return new Promise(resolve => {
          API['loadSystemMenuListWithBusinessSystemId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }

            this.menuData[0].children = this.sort(data)
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })
      },
      //根据菜单id,加载所有按钮
      loadButtonListWithMenuIdData(code){
        let postData={
          "businessSystemMenuId": code
        }
        return new Promise(resolve => {
          API['loadButtonListWithMenuId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            this.tableData = data
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })
      },
      /*根据读取数据筛选控件可以识别的数据*/
      sort(data){
        let result = []
        //循环遍历取出子集
        if(data.length) {
          //查询不是主菜单的子菜单,arr为子菜单，id为有子菜单的ids
          let arr=[],id=[]
          data.forEach(item=>{
            item.label = item.menuName
            if (item.parentId!=0){
              arr.push(item)
              if (id.indexOf(item.parentId) == -1) {
                id.push(item.parentId)
              }
            }
          })
          //设置有子菜单的children
          id.forEach(d=>{
            data.forEach(item=>{
              if (d ==item.id) {
                item.children = []
              }
            })
          })
          //添加子菜单
          if (arr.length>0) {
            arr.forEach(a=>{
              data.forEach((item,index)=>{
                if (a.parentId == item.id) {
                  if(item.children) {
                    item.children.push(a)
                  }
                }
                // /*删除子菜单*/
                // if (item.parentId!=0) {
                //   data.splice(index,1)
                // }
              })
            })
            data.forEach((item,index)=>{
              /*删除子菜单 */
              if (item.parentId==0) {
                result.push(item)
              }
            })

          }
        }
        return result
      },
      //根据按钮id加载按钮信息
      loadButtonWithIdData(id){
        let postData={
          "id": id,  //业务系统菜单记录id
        }
        return new Promise(resolve => {
          API['loadButtonWithId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            if (data.menu) {
              this.saveData.menu = data.menu
            }
            if (data.menus) {
              this.saveData.menus = data.menus
            }
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })

      },
      //保存
      Save(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs['btndialog'].validate((valid) => {
          if (valid) {
            this.saveFlag = true
            let postData = this.saveData
            API['saveButton'](postData).then(response=>{
              const { message }=response;
              this.$message(message)
              let data = this.$refs.menutree.getCheckedNodes()
              this.loadButtonListWithMenuIdData(data[0].id)
              this.dialogVisible = false
              this.saveFlag = false
            }).catch(error => {
              this.$message(error)
              this.saveFlag = false
            })
          } else {
            return false;
          }
        });

      },//
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveData.sort;
        obj=Number.parseInt(obj);
        this.saveData.sort=obj;
      }
    },
    watch:{
      "dialogVisible"(){
        if (this.dialogVisible==false){
          this.$nextTick(() => {
            this.$refs.btndialog.resetFields();
          })
        }

      }
    }
  }
</script>
<style>

</style>
<style scoped>

  .list{
    display: flex;flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    padding-left: 120px;
    text-align: left;
  }
  .list .item {
    font-size: 14px;
    font-weight: 400;
    line-height: 30px;
    /*width: 150px;*/
    height:30px;
    background-color: #efefef;
    padding:0 5px;
    border-radius:5px;
    overflow: hidden;
    margin-bottom: 10px;
    text-align: center;
  }
  .list .title{
    margin-right: 10px;
    float: left;
  }
  .list .delete{
    line-height: 30px;
    margin-left: 10px;
    color:red;
    float: right;
    cursor: pointer;
  }
  .wrapper{
    display: flex;
    flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    height:500px;
    overflow-y: auto;
  }

  .wrapper{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .icon{
    flex:1;
    width:100px;
    height: 30px;
  }
</style>
